<?php
namespace App\Base\Controllers;

use Aliyun\Api\Sms\Request\V20170525\SendSmsRequest;
use Aliyun\Core\DefaultAcsClient;
use Aliyun\Core\Profile\DefaultProfile;
use App\Base\Contracts\AreaInterface;
use App\Base\Contracts\PublicInterface;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\URL;


/**
 * Created by 荣耀电竞.
 * User: 林子彦 <278805354@qq.com>
 * Date: 2018/2/6 0006
 * Time: 11:12
 */
class PublicController extends Controller
{


    static $acsClient = null;

    /**
     * 取得AcsClient
     *
     * @return DefaultAcsClient
     */
    public static function getAcsClient() {
        //产品名称:云通信短信服务API产品,开发者无需替换
        $product = "Dysmsapi";

        //产品域名,开发者无需替换
        $domain = "dysmsapi.aliyuncs.com";

        // TODO 此处需要替换成开发者自己的AK (https://ak-console.aliyun.com/)
        $accessKeyId = "LTAIMl84HOg91XxG"; // AccessKeyId

        $accessKeySecret = "N1W0qrmOFme0GRedFkCMfHQ2ehWEDZ"; // AccessKeySecret

        // 暂时不支持多Region
        $region = "cn-hangzhou";

        // 服务结点
        $endPointName = "cn-hangzhou";


        if(static::$acsClient == null) {

            //初始化acsClient,暂不支持region化
            $profile = DefaultProfile::getProfile($region, $accessKeyId, $accessKeySecret);

            // 增加服务结点
            DefaultProfile::addEndpoint($endPointName, $region, $product, $domain);

            // 初始化AcsClient用于发起请求
            static::$acsClient = new DefaultAcsClient($profile);
        }
        return static::$acsClient;
    }

    /**
     * @return PublicInterface
     */
    public function getPublicInterface(){
        return app()->make(PublicInterface::class);
    }

    /**
     * 获取地址接口
     * @return AreaInterface
     */
    public function getAreaInterface(){
        return app()->make(AreaInterface::class);
    }
    /**
     * 图片上传
     */
    public function uploadPic(Request $request){
        if ($request->isMethod('post')) {


            $file = $request->file('file');
            // 文件是否上传成功
            if ($file->isValid()) {
                if ($info = $this->getPublicInterface()->savePicture($file)) {
                    if(get_config_param_value("QINIU_UPLOAD_IS_STATUS")) {  //是否开启七牛上传
                        $info["src"] = $info["token"];
                    }else{

                        $url=$request->getScheme()."://".$request->getHost().':'.$_SERVER["SERVER_PORT"];//URL::previous();  //请求网址
                        $info["src"] = $url.$info['path'];
                    }
                    return $info;
                } else {
                    throw  new ApiException([20001,"上传失败."]);
                }
                exit();
            }
        }
    }

    /**
     * 图片上传
     */
    public function uploadPicEdit(Request $request){
        if ($request->isMethod('post')) {

            $file = $request->file('imgFile');
            // 文件是否上传成功
            if ($file->isValid()) {
                if ($info = $this->getPublicInterface()->savePicture($file)) {
                    $url=$request->getScheme()."://".$request->getHost().':'.$_SERVER["SERVER_PORT"];//URL::previous();  //请求网址
                    if(get_config_param_value("QINIU_UPLOAD_IS_STATUS")) {  //是否开启七牛上传
                        $info["src"] = $info["token"];
                    }else{
                        $info["src"] = $url.$info['path'];
                    }
                    $arr=array();
                    $arr['error']=0;
                    $arr['url']= $info["src"];
                    echo json_encode($arr);
                    exit;
                } else {
                    $arr=array();
                    $arr['error']=1;
                    $arr['message']="上传失败";
                    echo json_encode($arr);
                    exit;
                }
                exit();
            }
        }
    }


    /**
     * 微信语音上传
     * @param Request $request
     */
    public function wxUploadVideo(Request $request){
        if ($request->isMethod('post')) {
            $file = $request->file('audioData'); //语音文件

            $info = $this->getPublicInterface()->wxSaveVedio($file);
            return $info;
        }

    }

    public function uploadVideo(Request $request){
        if ($request->isMethod('post')) {
            $file = $request->file('file'); //语音文件
            // 文件是否上传成功
            if ($file->isValid()) {
                if ($info = $this->getPublicInterface()->saveVedio($file)) {
                    if(get_config_param_value("QINIU_UPLOAD_IS_STATUS")) {  //是否开启七牛上传
                        $info["src"] = $info["token"];
                    }else{

                        $url=$request->getScheme()."://".$request->getHost().':'.$_SERVER["SERVER_PORT"];//URL::previous();  //请求网址
                        $info["src"] = $url.$info['path'];
                    }
                    return $info;
                } else {
                    throw  new ApiException([20001,"上传失败."]);
                }
                exit();
            }
        }
    }

    /**
     * 发送手机号
     */
    public function sendMobile(){

    }

    /**
     * 获取地区
     * @param Request $request
     * @return mixed
     */
    public function getAreaList(Request $request){
         return $this->getAreaInterface()->getAreaList($request->all());
    }

    /**
     * 获取三级
     * @param Request $request
     * @return mixed
     */
    public function getAreaListLevel(Request $request){
        return $this->getAreaInterface()->getAreaListLevel($request->all());
    }

    /**
     * 发送短信
     * @param Request $request
     */
    public function sendSms(Request $request){

        // 初始化SendSmsRequest实例用于设置发送短信的参数
        $request = new SendSmsRequest();

        //可选-启用https协议
        //$request->setProtocol("https");

        // 必填，设置短信接收号码
        $request->setPhoneNumbers("13400998080");

        // 必填，设置签名名称，应严格按"签名名称"填写，请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/sign
        $request->setSignName("新超人帮");

        // 必填，设置模板CODE，应严格按"模板CODE"填写, 请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/template
        $request->setTemplateCode("SMS_150738530");

        // 可选，设置模板参数, 假如模板中存在变量需要替换则为必填项
        $request->setTemplateParam(json_encode(array(  // 短信模板中字段的值
            "code"=>"12345",
            "product"=>"dsd"
        ), JSON_UNESCAPED_UNICODE));

        // 可选，设置流水号
        // $request->setOutId("yourOutId");

        // 选填，上行短信扩展码（扩展码字段控制在7位或以下，无特殊需求用户请忽略此字段）
        $request->setSmsUpExtendCode("1234567");

        // 发起访问请求
        $acsResponse = static::getAcsClient()->getAcsResponse($request);

        return $acsResponse;
    }

}